package top.frsf.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.frsf.reggie.entity.Category;
import top.frsf.reggie.entity.Dish;
import top.frsf.reggie.entity.Setmeal;
import top.frsf.reggie.excpetion.BusinessException;
import top.frsf.reggie.mapper.CategoryMapper;
import top.frsf.reggie.service.CategoryService;
import top.frsf.reggie.service.DishService;
import top.frsf.reggie.service.SetmealService;

/**
 * @Author FRSF
 * @Date 2023/1/14 23:56
 * @Description TODO
 */

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;


    /**
     * @Author: FRSF
     * @Date: 2023/1/15 0:46
     * @Description 根据ID删除分类，但删除之前需要进行关联判断
     * @param id: 分类ID
     * @return: void
     */
    @Override
    public void remove(Long id) {
        // 查询当前分类是否关联了菜品，若关联则抛出业务异常
        LambdaQueryWrapper<Dish> dishWrapper = new LambdaQueryWrapper<>();
        dishWrapper.eq(Dish::getCategoryId, id);
        long dishCount = dishService.count(dishWrapper);
        if (dishCount > 0) {
            throw new BusinessException("当前分类下关联了菜品，不能删除");
        }


        // 查询当前分类是否关联了菜品，若关联则抛出业务异常
        LambdaQueryWrapper<Setmeal> setmealWrapper = new LambdaQueryWrapper<>();
        setmealWrapper.eq(Setmeal::getCategoryId, id);
        long setmealCount = setmealService.count(setmealWrapper);
        if (setmealCount > 0) {
            throw new BusinessException("当前套餐下关联了菜品，不能删除");
        }

        // 正常删除分类
        super.removeById(id);
    }
}
